package at.fhooe.SRWCProject.Bluetooth;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import at.fhooe.SRWCProject.MainActivity;
import at.fhooe.SRWCProject.R;

/**
 * Created with IntelliJ IDEA. User: Vladimir Date: 1/28/14 Time: 4:06 PM To change this template
 * use File | Settings | File Templates.
 */
public class ChatActivity extends ListActivity {

	private String macAddress = "12:68:3f:7e:dc:81";
	public static final int MESSAGE_TO_SEND = 123;

	static ArrayList<at.fhooe.SRWCProject.Bluetooth.Message> messages;
	static AwesomeAdapter adapter;
	EditText text;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);

		Intent intent = getIntent();
		String status = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

		text = (EditText) findViewById(R.id.text);

		messages = new ArrayList<at.fhooe.SRWCProject.Bluetooth.Message>();

		adapter = new AwesomeAdapter(this, messages);
		setListAdapter(adapter); /**/

		addNewMessage(status, true);
	}

	private static void addNewMessage(String msg, Boolean isMine) {
		addNewMessage(new at.fhooe.SRWCProject.Bluetooth.Message(msg, isMine));
	}

	public void sendMessage(View v) {
		String newMessage = text.getText().toString().trim();
		if (newMessage.length() > 0) {
			text.setText("");
			addNewMessage(new at.fhooe.SRWCProject.Bluetooth.Message("Me: " + newMessage, true));
			MainActivity.sendMessage(newMessage);
			getListView().setSelection(messages.size() - 1);
		}
	}

	static void addNewMessage(at.fhooe.SRWCProject.Bluetooth.Message m) {
		messages.add(m);
		adapter.notifyDataSetChanged();
		// getListView().setSelection(messages.size() - 1);
	}

	public static Handler mHandler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message message) {
			switch (message.what) {
			case MESSAGE_TO_SEND: {
				String msg = (String) message.obj;
				addNewMessage(msg, false);
				break;
			}
			}
			return true;
		}
	});

}
